{$A8,B-,C+,D+,E-,F-,G+,H+,I+,J-,K-,L+,M-,N+,O+,P+,Q-,R-,S-,T-,U-,V+,W-,X+,Y+,Z1}
{$WARN UNSAFE_TYPE OFF}

unit DatabaseInterface;

interface

  uses
    Interface_TLB,
    ComObj,
    ExtActns,
    SQLiteWrap;

  type
    TDatabaseInterface = class(TAutoIntfObject, IDatabaseIntf, IDispatch)
      private
        fDatabase : TSQLiteDatabase;
      protected
        function Query(const query: WideString): OleVariant; safecall;
      public
        constructor Create(var Database : TSQLiteDatabase);
        destructor Destroy(); override;
    end;

implementation

  uses
    ActiveX,
    SysUtils,
    StringUtils,
    Variants,
    SQLResultInterface,
    Windows;

  constructor TDatabaseInterface.Create(var Database : TSQLiteDatabase);
  var
    TypeLib : ITypeLib;
    ExeName : WideString;
  begin
    //Get name of application
    ExeName := ParamStr(0);
    //Load type library from application's resources
    OleCheck(LoadTypeLib(PWideChar(ExeName), TypeLib));
    //Inherit
    inherited Create(TypeLib, IDatabaseIntf);
    //Set database
    fDatabase := Database;
  end;

  destructor TDatabaseInterface.Destroy();
  begin
    inherited;
    fDatabase.Free();
  end;

  function TDatabaseInterface.Query(const query: WideString) : OleVariant;
  var
    Table : TSqliteTable;
    ErrorMessage : Widestring;
  begin
    Table := nil;
    try
      try
        Table := fDatabase.GetTable(UTF8Encode(query));
      except on E : Exception do
        ErrorMessage := E.Message;
      end;
      Result := IDispatch(TSQLResult.Create(Table, ErrorMessage));
    except
      Result := VarAsType(Result, varEmpty);
    end;
  end;

end.
